package com.hibase.core.rule.service.ruledatasource.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.hibase.core.mybatis.service.BaseServiceImpl;
import com.hibase.core.rule.constant.RuleDataSourceType;
import com.hibase.core.rule.entity.ruledatasource.RuleDataSource;
import com.hibase.core.rule.entity.ruledatasource.vo.RuleDataSourceSearchVO;
import com.hibase.core.rule.mapper.ruledatasource.RuleDataSourceMapper;
import com.hibase.core.rule.service.ruledatasource.RuleDataSourceService;
import com.hibase.common.exception.HibaseAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 描述:
 * 规则数据源配置 实现类
 *
 * @author li-wei-hua
 * @date 2020-03-23 11:39
 */
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class RuleDataSourceServiceImpl extends BaseServiceImpl<RuleDataSourceMapper, RuleDataSource> implements RuleDataSourceService {

    @Autowired
    private DynamicDataSourceProperties dataSourceProperties;

    @Override
    public PageInfo selectDataSourceList(RuleDataSourceSearchVO searchVO) {
        QueryWrapper<RuleDataSource> queryWrapper = new QueryWrapper<>();
        // 查询条件
        if (StrUtil.isNotBlank(searchVO.getType())){
            queryWrapper.eq("type",searchVO.getType());
        }
        if (StrUtil.isNotBlank(searchVO.getPollName())){
            queryWrapper.eq("poll_name",searchVO.getPollName());
        }

        return super.page(searchVO, queryWrapper);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String changeDataSource(RuleDataSource dataSource) {

        // step 1. 重名校验(范围包含本地服务默认配置加载的)
        HibaseAssert.isFalse(dataSourceProperties.getDatasource().containsKey(dataSource.getPollName()),"默认数据源中已存在,请修改名称");
        RuleDataSource pollName = super.getOne(new QueryWrapper<RuleDataSource>().eq("poll_name", dataSource.getPollName()));
        // 名称不存在（排除自身）
        HibaseAssert.isTrue(pollName==null||(StrUtil.isNotBlank(dataSource.getId()) && pollName.getId().equals(dataSource.getId())),"动态数据源中已存在，请修改名称");

        // step 2. 设置数据库驱动
        dataSource.setDriverClassName(RuleDataSourceType.valueOf(dataSource.getType()).getDriverClassName());

        // step 2.1 加密密码
        //DES des = SecureUtil.des(CommConstant.SECURE_KEY.getBytes());
        //dataSource.setPassword(des.encryptHex(dataSource.getPassword()));
        // step 3. 更新数据
        super.store(dataSource);
        return dataSource.getId();
    }
}
